package com.icode.web.validator;

import com.icode.core.dto.user.PasswordHandelDTO;
import com.icode.core.dto.user.UserDTO;
import com.icode.core.model.user.User;
import com.icode.core.shared.SecurityUtil;
import com.icode.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.lang.annotation.Annotation;

/**
 * Created with IntelliJ IDEA.
 * User: lb
 * Date: 15-12-11
 * Time: 上午10:47
 * To change this template use File | Settings | File Templates.
 */
@Component
public class PasswordHandleValidator implements Validator {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public boolean supports(Class<?> clazz) {
        return PasswordHandelDTO.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        PasswordHandelDTO dto = (PasswordHandelDTO) target;
        User user = SecurityUtil.currentUser();
        String passwordFound = user.getPassword();
        String password = dto.getPassword();

        String newPassword = dto.getNewPassword();
        String reNewPassword = dto.getReNewPassword();

        if (!passwordEncoder.matches(password, passwordFound)) {
            errors.rejectValue("password", null, " ");
        }
        if(!newPassword.equals(reNewPassword)){
            errors.rejectValue("reNewPassword", null, " ");
        }
    }
}
